package ru.gelin.android.multiplier;

import android.app.Fragment;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;

public class CalcFragment extends Fragment {

    Operation operation;

    TextView num1Input;
    TextView num2Input;
    TextView result;
    ViewGroup operationsGroup;
    CompoundButton mulButton;
    CompoundButton divButton;

    boolean resuming = false;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        operation = new Operation();
        operation.setType(Operation.Type.MUL);  //TODO restore state
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.calc_fragment, container, false);

        this.num1Input = (TextView)view.findViewById(R.id.num1);
        this.num2Input = (TextView)view.findViewById(R.id.num2);
        this.result = (TextView)view.findViewById(R.id.result);
        this.operationsGroup = (ViewGroup)view.findViewById(R.id.operations_group);
        this.mulButton = (CompoundButton)view.findViewById(R.id.mul_button);
        this.divButton = (CompoundButton)view.findViewById(R.id.div_button);

        defineOperationListeners();
        defineNumbersListeners();

        return view;
    }

    @Override
    public void onPause() {
        super.onPause();

        MainActivity activity = (MainActivity)getActivity();
        activity.getHistory().add(this.operation);
    }

    @Override
    public void onResume() {
        super.onResume();

        this.resuming = true;

        MainActivity activity = (MainActivity)getActivity();
        OperationsHistoryItem item = activity.getHistory().getLatest();
        if (item != null) {
            this.operation = item.operation;     //TODO pass history item as args?
            bindOperationViews();
        }

        this.resuming = false;
        updateResult();
    }

    void defineOperationListeners() {
        this.mulButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                changeOperationType(Operation.Type.MUL, (CompoundButton)view);
            }
        });
        this.divButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                changeOperationType(Operation.Type.DIV, (CompoundButton)view);
            }
        });
    }

    void defineNumbersListeners() {
        TextWatcher listener = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
                //pass
            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
                //pass
            }
            @Override
            public void afterTextChanged(Editable editable) {
                updateResult();
            }
        };

        num1Input.addTextChangedListener(listener);
        num2Input.addTextChangedListener(listener);
    }

    void changeOperationType(Operation.Type type, CompoundButton button) {
        this.operation.setType(type);
        int childCount = this.operationsGroup.getChildCount();
        for (int i = 0; i < childCount; i++) {
            CompoundButton child = (CompoundButton)this.operationsGroup.getChildAt(i);
            child.setChecked(false);
        }
        button.setChecked(true);
        updateResult();
    }

    void updateResult() {
        if (this.resuming) {
            return;
        }
        try {
            double n1 = Double.parseDouble(String.valueOf(this.num1Input.getText()));
            double n2 = Double.parseDouble(String.valueOf(this.num2Input.getText()));
            this.operation.setNumber1(n1);
            this.operation.setNumber2(n2);
            this.result.setText(getString(R.string.result_format, this.operation.getResult())); //TODO i18n
        } catch (Throwable e) {
//            Toast.makeText(getActivity(), String.valueOf(e), Toast.LENGTH_SHORT).show();    //TODO remove
            this.result.setText(R.string.not_a_number);
        }
    }

    void bindOperationViews() {
        this.num1Input.setText(String.valueOf(this.operation.getNumber1()));    //TODO i18n
        this.num2Input.setText(String.valueOf(this.operation.getNumber2()));    //TODO i18n
        switch(this.operation.getType()) {
            case MUL:
                this.mulButton.setChecked(true);
                this.divButton.setChecked(false);
                break;
            case DIV:
                this.divButton.setChecked(true);
                this.mulButton.setChecked(false);
                break;
        }
        this.result.setText(getString(R.string.result_format, this.operation.getResult()));     //TODO i18n
    }

}
